{include file="public/header,public/nav,public/fixbar" title="订单支付-<?php echo request()->pc_info['seo_title']?>"/}
<style>
    .layui-col-xs4 .layui-form-radio, .layui-col-xs12 .layui-form-radio {
        width: 100%;
    }
</style>
<div class="layui-body">
    <div class="layui-container">
        <form class="layui-form order-prepare" autocomplete="off">
            {if $info.product_type == 1}
            <div class="layui-main margin-bottom-15">
                <div class="margin-bottom-15 space-between">
                    <h3 class="layui-font-18">确认收货地址</h3>
                    <div>
                        <a href="javascript:;" class="layui-btn layui-btn-primary layui-btn-sm address-add">使用新地址</a>
                        <a href="/user/address" class="layui-btn layui-btn-primary layui-btn-sm">管理地址</a>
                    </div>
                </div>
                <div class="address-list collapsed" id="addressList">
                    <div class="layui-row layui-col-space15">
                        {foreach $address_list as $key => $v}
                        <div class="layui-col-xs4 address-item">
                            <input type="radio" name="address_id" value="{$v.id}" lay-skin="none" {if $v.default == 1} checked {/if} lay-filter="address-radio-filter">
                            <div lay-radio class="lay-skin-checkcard lay-check-dot" style="height: 96px;">
                                <div class="lay-skin-checkcard-detail">
                                    <div class="layui-ellips layui-font-14">
                                        <div class="margin-bottom-10">
                                            <span class="font-weight-bold" style="font-size: 15px;">{$v.region} {$v.address}</span>
                                        </div>
                                        <div class="space-between">
                                            <div class="align-items-center">
                                                <span class="margin-right-10">{$v.name}，{$v.phone}</span>
                                                {if $v.default == 1}
                                                <span class="layui-badge layui-bg-red">默认</span>
                                                {/if}
                                            </div>
                                            <div data-id="{$v.id}" class="layui-btn layui-btn-primary layui-border-success layui-btn-sm address-edit"><i class="layui-icon layui-icon-edit"></i>编辑</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {/foreach}
                    </div>
                </div>
                <div class="margin-top-20 toggle-addresses">
                    <a href="javascript:;" class="align-items-center" id="toggleAddresses">
                        <span class="toggle-btn-text margin-right-5">显示全部地址</span><i class="layui-icon layui-font-14">&#xe61a;</i>
                    </a>
                </div>
            </div>
            {/if}
            <div class="layui-main margin-bottom-15">
                <div class="margin-bottom-15">
                    <h3 class="layui-font-18">确认订单信息</h3>
                </div>
                <table class="layui-table" lay-size="lg">
                    <colgroup>
                        <col>
                        <col width="260">
                        <col width="150">
                        <col width="100">
                    </colgroup>
                    <thead>
                        <tr style="background-color: #f8f8f8;">
                            <th>商品信息</th>
                            <th>商品属性</th>
                            <th>数量</th>
                            <th>价格</th>
                        </tr> 
                    </thead>
                    <tbody>
                        <tr>
                            <td>
                                <a href="{$info.href}">
                                    <div class="align-items-center">
                                        {if $info.product_type == 10}
                                            <div class="justify-content-center">
                                                <img style="background-color: {$info.background_color};margin-right: 0px;" src="{$info['head_imgs']}" class="user-goods-img">
                                                <span class="exam-sub-title">{$info.sub_title}</span>
                                            </div>
                                        {else}
                                            <img class="{if $info.product_type == 1}user-goods-img{else}user-course-img{/if}" src="{$info.head_imgs}">
                                        {/if}
                                        <div class="detail">
                                            <div class="product-title">
                                                <span class="item-title-label">{$info.product_type_text}</span>{$info.name}
                                            </div>
                                        </div>
                                    </div>
                                </a>
                            </td>
                            <td>{$info.attr.name}</td>
                            <td class="layui-font-16">x{$info.num}</td>
                            <td class="layui-font-16">
                                <div><span class="symbol">￥</span>{$info.attr.sale_price}</div>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div class="layui-elem-quote">
                    <h4 class="layui-font-14 margin-bottom-10">订单备注</h4> 
                    <input type="text" name="customer_notes" placeholder="请输入，付款后商家可见，建议和商家协商一致" value="" class="layui-input" lay-affix="clear">
                </div>
            </div>
            <div class="layui-main">
                <div class="margin-bottom-15">
                    <h3 class="layui-font-18">付款详情</h3>
                </div>
                <div class="order-info layui-font-16">
                    <div class="goods-info">
                        <div>商品总价</div>
                        <div class="layui-font-20"><span class="symbol">￥</span>{$price.priceData.price}</div>
                    </div>
                    <div class="goods-info">
                        <div>共减</div>
                        <div class="layui-font-red layui-font-18"><span class="symbol">￥</span><span class="total-discount">{$price.priceData.discountAmount}</span></div>
                    </div>
                    <div class="goods-info">
                        <div>优惠券</div>
                        <div id="couponList">
                            <a href="javascript:;">
                                <span class="text layui-font-16">无可用</span>
                                <i class="layui-icon layui-icon-right margin-left-5"></i>
                            </a>
                        </div>
                    </div>
                    {if $price.priceData.vipDiscountAmount > 0}
                    <div class="goods-info">
                        <div>会员折扣</div>
                        <div class="layui-font-red layui-font-18"><span class="symbol">￥</span>{$price.priceData.vipDiscountAmount}</div>
                    </div>
                    {/if}
                    {if $price.priceData.activityAmount > 0}
                    <div class="goods-info">
                        <div>活动优惠</div>
                        <div class="layui-font-red layui-font-18"><span class="symbol">￥</span>{$price.priceData.activityAmount}</div>
                    </div>
                    {/if}
                    {if $info.product_type == 1}
                    <div class="goods-info">
                        <div>运费</div>
                        <div class="layui-font-red layui-font-18"><span class="symbol">￥</span><span class="shipping-fee">{$price.priceData.shippingFee}</span></div>
                    </div>
                    {/if}
                </div>
                <div class="hand-order-button layui-font-16">
                    <div class="total-info">
                        <div>实付款：</div>
                        <div class="layui-font-red layui-font-28 font-weight-bold">
                            <span class="symbol">￥</span><span class="pay-price">{$price.priceData.payAmount}</span>
                        </div>
                    </div>
                    <button type="button" class="layui-btn layui-bg-red layui-btn-xl width-220 buy-button">
                        确认购买
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
<!-- 优惠券 -->
<div id="couponMoulde" class="scrollbar" style="display: none;background-color: #f2f2f2;height: 549px;border-radius: 0 0 12px 12px;">
    <div class="layui-row layui-padding-3">
        <form class="layui-form" autocomplete="off">
            <div class="layui-col-space10">
                {if $price.user_coupon}
                    {foreach $price.user_coupon as $key => $v}
                    <div class="layui-col-xs12 coupon-item">
                        <input type="radio" name="user_coupon_id" value="{$v.id}" lay-skin="none" {if $key == 0} checked {/if} lay-filter="coupon-radio-filter">
                        <div lay-radio class="lay-skin-checkcard lay-check-dot" style="padding: 0px;">
                            <div class="lay-skin-checkcard-detail">
                                <div class="coupon-card" style="background-color: #fff;align-items: unset;">
                                    <div class="card-left" style="color: #ff5722;">
                                        <div class="price-number">{$v.discount_amount}<span class="price-symbol">元</span></div>
                                        <div class="coupon-type">{if $v.discount_type == 1} 立减 {else} 满减 {/if}</div>
                                    </div>
                                    <div class="card-right layui-ellip">
                                        <p class="coupon-title layui-ellip">{$v.coupon_name}</p>
                                        <strong class="card-time">有效期至 {$v.coupon.valid_end_time}</strong>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    {/foreach}
                {else}
                    <div class="layui-empty"><img src="/static/images/nodata/no_coupon.png"><p>暂无可用优惠券~</p></div>
                {/if}
            </div>
        </form>
    </div>
</div>
<!-- 选择支付 -->
<div id="paySelectMoulde" style="display: none;background-color: #f2f2f2;height: 549px;border-radius: 0 0 12px 12px;">
    <div class="layui-container" style="width: 100%;">
        <div class="layui-main">
            <div class="layui-row">
                <form class="layui-form" autocomplete="off">
                    <div class="zent-block-header block-header margin-bottom-5" style="padding: 0;">
                        <div class="zent-block-header__title zent-block-header__title-ribbon">
                            <h3>购买商品</h3>
                        </div>
                    </div>
                    <div class="layui-elem-quote layui-font-16 margin-bottom-30">
                        <div class="item">
                            {if $info.product_type == 10}
                                <div class="justify-content-center">
                                    <img style="background-color: {$info.background_color};margin-right: 0px;" src="{$info['head_imgs']}" class="user-goods-img" style="width: 60px;height: 60px;">
                                    <span class="exam-sub-title">{$info.sub_title}</span>
                                </div>
                            {else}
                                <img class="user-goods-img" src="{$info.head_imgs}" style="width: 60px;height: 60px;">
                            {/if}
                            <div class="detail layui-ellip" style="width: 100%;">
                                <div class="product-title space-between">
                                    <p class="layui-ellip">
                                        <span class="item-title-label">{$info.product_type_text}</span>
                                        {$info.name}
                                    </p>
                                    <div>￥{$info.attr.sale_price}</div>
                                </div>
                                <div class="space-between" style="margin-top: 10px;color:#7a7a7a;">
                                    <p class="layui-font-14">规格：{$info.attr.name}</p>
                                    <p>x1</p>
                                </div>
                            </div>
                        </div>
                        <div class="align-items-center margin-top-20">
                            <div>应付金额：</div>
                            <div class="layui-font-red layui-font-28">
                                <span class="symbol">￥</span><span class="pay-price">{$price.priceData.payAmount}</span>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item layui-col-space10">
                        <div class="layui-col-xs4">
                            <input type="radio" name="pay_type" value="1" lay-skin="none" checked>
                            <div lay-radio class="lay-skin-checkcard lay-check-dot" style="height: 76px;">
                                <div class="lay-skin-checkcard-detail" style="line-height: 50px;">
                                    <div class="justify-content-center">
                                        <img style="width:34px;" class="margin-right-10" src="/static/images/order/wx-pay.png">
                                        <span class="layui-font-16">微信支付</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-xs4">
                            <input type="radio" name="pay_type" value="2" lay-skin="none" disabled>
                            <div lay-radio class="lay-skin-checkcard lay-check-dot" style="height: 76px;">
                                <div class="lay-skin-checkcard-detail" style="line-height: 50px;">
                                    <div class="justify-content-center">
                                        <img style="width:30px;" class="margin-right-10" src="/static/images/alipay.png">
                                        <span class="layui-font-16">支付宝支付</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="text-align-center" style="margin-top: 60px;margin-bottom: 60px;">
                        <button type="button" class="layui-btn layui-bg-red layui-btn-xl width-220" lay-submit lay-filter="payButton">
                            立即支付
                        </button>
                    </div>
                    <input type="hidden" name="product_id" value="{$info.id}">
                    <input type="hidden" name="attr_id" value="{$info.attr.id}">
                    <input type="hidden" name="num" value="{$info.num ? $info.num : 1}">
                    <input type="hidden" name="type" value="{$info.product_type}">
                    <input type="hidden" name="coupon_id" value="0">
                </form>
            </div>
        </div>
    </div>
</div>
<!-- 微信支付 -->
<div id="payWxcodeMoulde" style="display: none;background-color: #f2f2f2;height: 549px;border-radius: 0 0 12px 12px;">
    <div class="layui-container" style="width: 100%;">
        <div class="layui-main">
            <div class="layui-payment-wxcode">
                <div class="code-infor space-between">
                    <div class="code-infor-content">
                        <div class="justify-content-center">
                            <img src="/static/images/order/wx-pay.png">
                            <p class="margin-left-10">请使用微信扫一扫 <br> 扫二维码支付</p>
                        </div>
                        <div class="code-box" style="background-image: url(/static/images/order/wxpay-code.png);">
                            <div id="wxpay-qrcode">
                            </div>
                        </div>
                        <p class="tips"><span class="layui-font-success font-weight-bold number">5</span> 分钟后二维码失效，请尽快支付</p>
                    </div>
                    <img src="/static/images/order/phone.png" class="phone-img">
                </div>
                <div class="layui-font-success switch-button">[ 查看订单/更换支付方式 ]</div>
            </div>
        </div>
    </div>
</div> 
{include file="public/footer"/}
<script type="text/javascript">
    layui.use(['form','layer'], function(){
        var layer = layui.layer, form = layui.form, $ = layui.$;
        
        let product_id = $("input[name=product_id]").val();
        let attr_id = $("input[name=attr_id]").val();
        
        // 添加收货地址
        $(".address-add").click(function(){
            var index = layer.open({
                skin: 'layui-layer-radius', // 弹窗主题样式
                offset: 'auto',
                title: '新建收货地址',
                type: 2,
                anim: 'slideUp',
                shade: 0.3,
                shadeClose: true,
                area: ['620px', '500px'],
                content: '/user/address_edit'
            });
            var device = layui.device('mobile');
            if (device.mobile) {
                layer.full(index);
            }
        })

        // 编辑收货地址
        document.querySelectorAll('.address-edit').forEach(function(btn) {
            btn.addEventListener('click', function(e) {
                e.stopPropagation(); // 阻止事件冒泡，避免触发卡片选择
                var id = this.getAttribute('data-id');
                var index = layer.open({
                    skin: 'layui-layer-radius', // 弹窗主题样式
                    offset: 'auto',
                    title: '编辑收货地址',
                    type: 2,
                    anim: 'slideUp',
                    shade: 0.3,
                    shadeClose: true,
                    area: ['620px', '500px'],
                    content: '/user/address_edit?id='+id
                });
                var device = layui.device('mobile');
                if (device.mobile) {
                    layer.full(index);
                }
            });
        });

        // 初始化：如果地址数量少于等于3个，隐藏展开按钮
        if($('.address-item').length <= 3) {
            $('#toggleAddresses').hide();
            $('#addressList').removeClass('collapsed').addClass('expanded');
        }

        // 展开/收起地址
        $('#toggleAddresses').on('click', function(){
            var $addressList = $('#addressList');
            var $icon = $(this).find('.layui-icon');
            var $textSpan = $(this).find('.toggle-btn-text');
            
            if($addressList.hasClass('expanded')) {
                // 收起状态
                $addressList.removeClass('expanded').addClass('collapsed');
                $icon.html('&#xe61a;');
                $textSpan.text('显示全部地址');
            } else {
                // 展开状态
                $addressList.removeClass('collapsed').addClass('expanded');
                $icon.html('&#xe619;');
                $textSpan.text('收起全部地址');
            }
        });

        // 初始化价格计算
        $(function(){
            getCalcPrice()
        })

        // 选择收货地址
        form.on('radio(address-radio-filter)', function(data){
            var elem = data.elem; // 获得 radio 原始 DOM 对象
            var user_address_id = elem.value; // 获得 radio 值
            // 价格计算
            getCalcPrice();
        });

        // 选择优惠券
        form.on('radio(coupon-radio-filter)', function(data){
            var elem = data.elem; // 获得 radio 原始 DOM 对象
            var user_coupon_id = elem.value; // 获得 radio 值
            
            // 价格计算
            getCalcPrice();
        });

        // 价格计算
        function getCalcPrice() {
            var goods_num = $('input[name="num"]').val();
            var coupon_id = $('input[name="user_coupon_id"]:checked').val();
            var address_id = $('input[name="address_id"]:checked').val();
            var loading = layer.load();
            $.ajax({
                url:'/order/get_calc_price',
                type:'post',
                data:{"product_id":product_id, 'attr_id':attr_id, "num":goods_num, "coupon_id":coupon_id, "address_id":address_id},
                dataType:"JSON",
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                success:function(res){
                    layer.close(loading);  //返回数据关闭loading
                    if(res.code == 0){
                        // 更新页面价格
                        calcPriceSaveHtml(res.data.priceData);
                        layer.closeAll();
                    } else{
                        layer.msg(res.msg,{icon: 2});
                    }
                },
                error:function(e){
                    layer.close(loading);
                    layer.msg('请求失败'+e.responseText,{icon: 2});
                },
            });
        }

        // 选择优惠券
        $("#couponList").click(function(){
            var index = layer.open({
                skin: 'layui-layer-radius', // 弹窗主题样式
                offset: 'auto',
                title: '选择使用优惠券',
                type: 1,
                anim: 'slideUp',
                shade: 0.3,
                shadeClose: true,
                scrollbar: false,
                area: ['375px', '600px'],
                content: $("#couponMoulde"),
            });
            var device = layui.device('mobile');
            if (device.mobile) {
                layer.full(index);
            }
        })

        // 计算价格后价格更新
        function calcPriceSaveHtml(priceData) {
            var user_coupon_id = $('input[name="user_coupon_id"]:checked').val();

            var couponHtml = `<a href="javascript:;"><span class="text">无可用</span><i class="layui-icon layui-icon-right margin-left-5"></i></a>`;
            if (priceData.couponFee > 0) {
                couponHtml = `<a href="javascript:;"><span class="symbol layui-font-red">￥</span><span class="layui-font-18 layui-font-red">${priceData.couponFee}</span><i class="layui-icon layui-icon-right margin-left-5"></i></a>`
            }
            $("#couponList").html(couponHtml);
            $(".total-discount").text(priceData.discountAmount);
            $(".pay-price").text(priceData.payAmount);
            $("input[name=coupon_id]").val(user_coupon_id);
            $(".shipping-fee").text(priceData.shippingFee);
        }

        // 选择支付方式
        $(".buy-button").click(function(){
            selectPay();
        })
        function selectPay() {
            var index = layer.open({
                skin: 'layui-layer-radius', // 弹窗主题样式
                offset: 'auto',
                title: '选择支付方式',
                type: 1,
                anim: 'slideUp',
                shade: 0.3,
                area: ['800px', '600px'],
                content: $("#paySelectMoulde"),
            });
            var device = layui.device('mobile');
            if (device.mobile) {
                layer.full(index);
            }
        }

        // 创建订单
        form.on('submit(payButton)', function(data){
            var address_id = $('input[name="address_id"]:checked').val();
            var customer_notes = $('input[name="customer_notes"]').val();

            data.field.address_id = address_id;
            data.field.customer_notes = customer_notes;
            var loading = layer.load();
            $.ajax({
                url:'/order/create',
                type:'post',
                data:data.field,
                dataType:"JSON",
                success:function(res){
                    layer.close(loading);  //返回数据关闭loading
                    if(res.code == 0){
                        getPayInfo(res.data);
                    }
                    else{
                        layer.msg(res.msg,{icon: 2});
                    }
                },
                error:function(e){
                    layer.close(loading);
                    layer.msg('请求失败'+e.responseText,{icon: 2});
                },
                
            });
            return false;
        });

        // 支付信息
        function getPayInfo(data) {
            var pay_type = $('input[name="pay_type"]:checked').val();
            if (pay_type == 1) {
                layer.closeAll();
                $("#wxpay-qrcode").html('<img src="'+data.qrcode_url+'">')
                // 微信支付
                var index = layer.open({
                    skin: 'layui-layer-radius', // 弹窗主题样式
                    offset: 'auto',
                    title: '微信支付',
                    type: 1,
                    anim: 'slideUp',
                    shade: 0.3,
                    area: ['800px', '600px'],
                    content: $("#payWxcodeMoulde"),
                    success: function(layero, index, that){
                        checkOrderPay(data.order_id);
                        $('.switch-button').attr('data-id', data.order_id);
                    },
                    end: function(){
                        clearInterval(timer);
                    }
                    
                });
            }
        }

        // 更换支付方式
        $(".switch-button").click(function(){
            layer.closeAll();
            clearInterval(timer);
            var id = $(this).data('id');
            location.href = '/user/order_detail?order_id='+id;
        })

        // 定时器变量
        var timer = null;

        // 检查订单是否支付
        function checkOrderPay(order_id) {
            timer = setInterval(function () {
                $.ajax({
                    url:'/order/check_order_pay',
                    type:'post',
                    data:{"order_id":order_id},
                    dataType:"JSON",
                    success:function(res){
                        if(res.code == 0){ // 支付成功
                            layer.msg(res.msg,{icon: 1,time:1500},function(){
                                layer.closeAll();
                                location.href = '/user/order';
                            })
                        }
                    }
                });
            }, 5000);
        }
    })
</script>